package com.gp.study.mybatis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GPExecutor {
	
	private GpConfigurattion configurattion;
	
	public GPExecutor(GpConfigurattion configurattion) {
		this.configurattion = configurattion;
	}
	
	public Connection openConnection() throws ClassNotFoundException, SQLException{
		String DRIVER_NAME = configurattion.sqlMappings.getString("driver.name");
		String DB_URL = configurattion.sqlMappings.getString("myql.url");
		String USER_NAME = configurattion.sqlMappings.getString("mysql.username");
		String PASSWORD = configurattion.sqlMappings.getString("mysql.password");
		Class.forName(DRIVER_NAME);
		Connection connection = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
		return connection;
	}

	public <T> T query(String sql, Object parm) throws ClassNotFoundException, SQLException {
		Connection conn = openConnection();
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1,parm.toString());
		ResultSet rs = stmt.executeQuery();
		return handlerResultSet(rs);
	}

	private <T> T handlerResultSet(ResultSet rs) throws SQLException {
		User user = new User();
		while(rs.next()){
			user.setId(rs.getInt("id"));
			user.setName(rs.getString("name"));
			user.setAge(rs.getInt("age"));
		}
		return (T) user;
	}

}
